package com.mzpai.web.controller;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.mzpai.product.constant.ProductConstants;
import com.mzpai.product.exception.ProductResException;
import com.mzpai.product.exception.ProductResExceptionCode;
import com.mzpai.product.model.StoreBrand;
import com.mzpai.product.model.StoreCategory;
import com.mzpai.product.model.StoreProductAttrSupplier;
import com.mzpai.product.model.StoreProductAttrValueSupplier;
import com.mzpai.product.model.StoreProductDetailsSupplier;
import com.mzpai.product.model.StoreProductSupplier;
import com.mzpai.product.model.SystemSetting;
import com.mzpai.product.service.StoreBrandService;
import com.mzpai.product.service.StoreCategoryService;
import com.mzpai.product.service.StoreProductAttrSupplierService;
import com.mzpai.product.service.StoreProductAttrValueSupplierService;
import com.mzpai.product.service.StoreProductDetailsSupplierService;
import com.mzpai.product.service.StoreProductService;
import com.mzpai.product.service.StoreProductSupplierService;
import com.mzpai.product.service.SystemSettingService;
import com.mzpai.product.util.SearchUtil;
import com.mzpai.product.vo.CopyStoreProductSupplierReqVo;
import com.mzpai.product.vo.StoreProductSupplierDto;
import com.mzpai.product.vo.StoreProductSupplierReqVo;
import com.mzpai.product.vo.StoreProductSupplierVo;
import com.mzpai.util.BeanUtils;
import com.mzpai.util.DateUtil;
import com.mzpai.util.StringUtils;
import com.mzpai.vo.ResponseVo;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
/**
 *
 * <b>供应商商品表 | Controller</b><br>
 *
 * guguanfei 2021-03-16 14:43:32
 * 
 *  @version 1.0.0
 *
 */
@Api(value = "商品库数据接口")
@RestController
@RequestMapping("/storeProductSupplier")
public class StoreProductSupplierController extends BaseController {

	private static Logger log = LoggerFactory.getLogger(StoreProductSupplierController.class);
	@Autowired 
	private StoreProductSupplierService storeProductSupplierService;
	
	@Autowired 
	private StoreProductService storeProductService;
	
	@Autowired
	private StoreCategoryService storeCategoryService;
	@Autowired
	private SystemSettingService systemSettingService;
	
	@Autowired
	private StoreProductDetailsSupplierService storeProductDetailsSupplierService;
	
	@Autowired
	private StoreProductAttrValueSupplierService storeProductAttrValueSupplierService;
	
	@Autowired
	private StoreProductAttrSupplierService storeProductAttrSupplierService;
	
	@Autowired
	private StoreBrandService storeBrandService;
	
	
	@ApiOperation(value = "根据条件分页查询基础商品库数据")
    @RequestMapping(value = "/queryProductSupplierByPage", method = {RequestMethod. POST ,RequestMethod. GET })
    public ResponseVo<PageInfo<StoreProductSupplierDto>> queryProductSupplierByPage(
    		@ApiParam(required = true, name = "storeProductSupplierStr", value = "入参为storeProductSupplierStr")
    		@RequestParam(value = "storeProductSupplierStr", required = true) String storeProductSupplierStr){
		
		log.info("msg1=开始根据条件分页查询基础商品库数据,,method=queryProductSupplierByPage,,reqVo={}",storeProductSupplierStr);
		StoreProductSupplierReqVo storeProductSupplierReqVo = JSONObject.parseObject(storeProductSupplierStr, StoreProductSupplierReqVo.class);
		
		String cateIdStr=storeProductSupplierReqVo.getCateId();
		Integer pageIndex=storeProductSupplierReqVo.getPageIndex();
		Integer pageSize=storeProductSupplierReqVo.getPageSize();
		String storeNameOrBarCode=storeProductSupplierReqVo.getStoreNameOrBarCode();
		Integer storeId=storeProductSupplierReqVo.getStoreId();
		//门店是否复制过 0未复制 1已复制
		String copyFlage=storeProductSupplierReqVo.getCopyFlage();
		//默认查询 未复制
		if(StringUtils.isNullOrBlank(copyFlage)){
			copyFlage=ProductConstants.COPY_FLAGE_0;
		}
		if(storeId==null){
			ResponseVo<PageInfo<StoreProductSupplierDto>> resultVo=new ResponseVo<PageInfo<StoreProductSupplierDto>>();
			resultVo.setCode(ProductResExceptionCode.STOREID_NULL.getCode());
			resultVo.setMessage(ProductResExceptionCode.STOREID_NULL.getMessage());
			return resultVo;
		}
		List<String> cateIdList=null;
		
		if(!StringUtils.isNullOrBlank(cateIdStr)){
			cateIdList=new ArrayList<String>();
			String cateIdArray[]=cateIdStr.split(",");
			for(String cateStr:cateIdArray){
				cateIdList.add(cateStr);
			}
		}
		logger.info("msg1=查询商户下商品开始时间={}", DateUtil.getNow());
		List<String> storeProductCodeList=storeProductService.getProductCodeList(storeId);
		logger.info("msg1=查询商户下商品结束时间={}", DateUtil.getNow());
		//根据叶子节点id查询商品id
		Map<String,Object> map=new HashMap<String,Object>();
//		map.put("factoryId", FACTORY_CONTANT);
		if(cateIdList!=null && !cateIdList.isEmpty()){
			map.put("cateIdList", cateIdList);
		}
		//分词器开关， 设置 1 开启
		SystemSetting systemSetting = systemSettingService.getSettingByCode("search-switch");
		if(systemSetting != null && "1".equals(systemSetting.getValue()) && StringUtils.isNoneBlank(storeNameOrBarCode)) {
			logger.info("msg1=查询分词器开始时间={}", DateUtil.getNow());
			String stmp = SearchUtil.search(storeNameOrBarCode);
			logger.info("msg1=查询分词器结束时间={}", DateUtil.getNow());
			logger.info("开放搜索返回商品id={}", stmp);
			if(StringUtils.isNoneBlank(stmp)) {
				map.put("productIds", stmp.split(","));
			}
		} else if(StringUtils.isNoneBlank(storeNameOrBarCode)){
			map.put("storeName", storeNameOrBarCode);
		}
		//查询未复制过的
		if(storeProductCodeList!=null && !storeProductCodeList.isEmpty()&& copyFlage.equals(ProductConstants.COPY_FLAGE_0)){
			map.put("productCodeNotInList", storeProductCodeList);
		}
		if(storeProductCodeList!=null && !storeProductCodeList.isEmpty()&& copyFlage.equals(ProductConstants.COPY_FLAGE_1)){
			map.put("productCodeInList", storeProductCodeList);
		}
		logger.info("msg1=查询商品信息开始时间={}", DateUtil.getNow());
		PageInfo<StoreProductSupplierDto> storeProductSupplierPageInfo=storeProductSupplierService.getProcuctAndBrandList(map, pageIndex, pageSize);
		logger.info("msg1=查询商品信息结束时间={}", DateUtil.getNow());
		List<StoreProductSupplierDto> listStoreProductSupplier=storeProductSupplierPageInfo.getList();
		
		if(listStoreProductSupplier!=null && listStoreProductSupplier!=null && !listStoreProductSupplier.isEmpty()){
			
			for(StoreProductSupplierDto storeProductSupplierDto:listStoreProductSupplier){
				
				String productCode=storeProductSupplierDto.getProductCode();
				
				if(!StringUtils.isNullOrBlank(productCode) && storeProductCodeList!=null && !storeProductCodeList.isEmpty() && storeProductCodeList.contains(productCode)){
					storeProductSupplierDto.setCopyFlage(ProductConstants.COPY_FLAGE_1);
				}else{
					storeProductSupplierDto.setCopyFlage(ProductConstants.COPY_FLAGE_0);
				}
			}
	      }
		ResponseVo<PageInfo<StoreProductSupplierDto>> resVo=new ResponseVo<PageInfo<StoreProductSupplierDto>>();
		resVo.setResult(storeProductSupplierPageInfo);
		log.info("msg1=结束根据条件分页查询基础商品库数据,,method=queryProductSupplierByPage");
    	return resVo;
    }
	
	
	@ApiOperation(value = "根据商品编码查询商品库详情")
    @RequestMapping(value = "/queryProductSupplierById", method = RequestMethod.POST)
    public ResponseVo<StoreProductSupplierVo> queryProductSupplierById(
    		@ApiParam(required = true, name = "id", value = "入参为商品id")
    		@RequestParam(value = "id", required = true) Integer id){
		
		log.info("msg1=根据商品编码查询商品库数据详情,,method=queryProductSupplierByProductCode,,reqVo={}",id);
		
		StoreProductSupplier storeProductSupplier=storeProductSupplierService.queryByPrimaryId(id);
		
		Map<String,Object> queryProductDetailsSupplierMap=new HashMap<String,Object>();
		queryProductDetailsSupplierMap.put("productId", id);
		List<StoreProductDetailsSupplier> storeProductDetailsSupplierList=storeProductDetailsSupplierService.getList(queryProductDetailsSupplierMap);
		
		Map<String,Object> attrValueSupplierMap=new HashMap<String,Object>();
		attrValueSupplierMap.put("productId", id);
		attrValueSupplierMap.put("type", ProductConstants.ACTIVE_TYPE_0);
		List<StoreProductAttrValueSupplier> attrValueSupplierList= storeProductAttrValueSupplierService.getList(attrValueSupplierMap);
		
		
		Map<String,Object> attrSupplierMap=new HashMap<String,Object>();
		attrSupplierMap.put("productId", id);
		attrSupplierMap.put("type", ProductConstants.ACTIVE_TYPE_0);
		List<StoreProductAttrSupplier> attrSupplierList= storeProductAttrSupplierService.getList(attrSupplierMap);
		
		StoreProductSupplierVo storeProductSupplierVo=new StoreProductSupplierVo();
		BeanUtils.copyProperties(storeProductSupplier, storeProductSupplierVo);
		
		
		Integer brandId=storeProductSupplierVo.getBrandId();
		StoreBrand storeBrand=storeBrandService.queryByPrimaryId(brandId);
		if(storeBrand!=null){
			storeProductSupplierVo.setBrandName(storeBrand.getBrandName());
		}
		
		
		String queryCateIdStr=storeProductSupplierVo.getCateId();
		String []cateIdarray=queryCateIdStr.split(",");
		StringBuffer cateNameSb=new StringBuffer();
		
		for(String cateid:cateIdarray){
			Integer cateId=Integer.valueOf(cateid);
			StoreCategory storeCategory=storeCategoryService.queryByPrimaryId(cateId);
			String cateName=storeCategory.getCateName();
			cateNameSb.append(cateName+",");
		}
		String cateName=cateNameSb.toString();
		if(!StringUtils.isNullOrBlank(cateName)){
			storeProductSupplierVo.setCateName(cateName.substring(0, cateName.lastIndexOf(",")+1));
		}
		
		storeProductSupplierVo.setStoreProductAttrSupplierList(attrSupplierList);
		storeProductSupplierVo.setStoreProductAttrValueSupplierList(attrValueSupplierList);
		storeProductSupplierVo.setStoreProductDetailsSupplierList(storeProductDetailsSupplierList);
		
		ResponseVo<StoreProductSupplierVo> resVo=new ResponseVo<StoreProductSupplierVo>();
		resVo.setResult(storeProductSupplierVo);
		
		log.info("msg1=根据商品编码查询商品库数据详情,,method=queryProductSupplierByProductCode");
    	return resVo;
    }


	
	@ApiOperation(value = "复制基础商品到店铺")
    @RequestMapping(value = "/copyProductSupplier", method = RequestMethod.POST)
    public ResponseVo copyProductSupplier(
    		@ApiParam(required = true, name = "copyStoreProductSupplierStr", value = "入参为copyStoreProductSupplierStr")
    		@RequestParam(value = "copyStoreProductSupplierStr", required = true) String copyStoreProductSupplierStr){
		
		CopyStoreProductSupplierReqVo copyStoreProductSupplierReqVo = JSONObject.parseObject(copyStoreProductSupplierStr, CopyStoreProductSupplierReqVo.class);
		
		log.info("msg1=复制基础商品到店铺开始,,method=copyProductSupplier,,reqVo={}",JSON.toJSONString(copyStoreProductSupplierReqVo));
		
		Integer storeId=copyStoreProductSupplierReqVo.getStoreId();
		List<Integer> producIdList=copyStoreProductSupplierReqVo.getProductIdList();
		if(storeId==null){
			ResponseVo resultVo=new ResponseVo();
			resultVo.setCode(ProductResExceptionCode.STOREID_NULL.getCode());
			resultVo.setMessage(ProductResExceptionCode.STOREID_NULL.getMessage());
			return resultVo;
//			throw new ProductResException(ProductResExceptionCode.STOREID_NULL.getCode(),ProductResExceptionCode.STOREID_NULL.getMessage());
		}
		
		if(producIdList==null || producIdList.isEmpty()){
			ResponseVo resultVo=new ResponseVo();
			resultVo.setCode(ProductResExceptionCode.PRODUCTCODE_LIST_NULL.getCode());
			resultVo.setMessage(ProductResExceptionCode.PRODUCTCODE_LIST_NULL.getMessage());
			return resultVo;
//			throw new ProductResException(ProductResExceptionCode.PRODUCTCODE_LIST_NULL.getCode(),ProductResExceptionCode.PRODUCTCODE_LIST_NULL.getMessage());
		}
		try{
			for(Integer productId:producIdList){
				StoreProductSupplier storeProductSupplier=storeProductSupplierService.queryByPrimaryId(productId);
				if(storeProductSupplier!=null){
					storeProductSupplierService.saveStoreProductCopyProductSupplier(storeProductSupplier,storeId);
				}
			}
		}catch(ProductResException e){
			ResponseVo resVo=new ResponseVo();
			resVo.setCode(e.getCode());
			resVo.setMessage(e.getMessage());
			return resVo;
		}catch(Exception e){
			e.printStackTrace();
			ResponseVo resultVo=new ResponseVo();
			resultVo.setCode(ProductResExceptionCode.SAVE_ERROR.getCode());
			resultVo.setMessage(ProductResExceptionCode.SAVE_ERROR.getMessage());
			return resultVo;
//			throw new ProductResException(ProductResExceptionCode.SAVE_ERROR.getCode(),ProductResExceptionCode.SAVE_ERROR.getMessage());
		}
		ResponseVo resVo=new ResponseVo();
		resVo.setCode(ProductResExceptionCode.SUCCESS.getCode());
		resVo.setMessage(ProductResExceptionCode.SUCCESS.getMessage());
		log.info("msg1=复制基础商品到店铺结束,,method=copyProductSupplier");
    	return resVo;
    }
	
	
	
	
	
	

}